package controllers

import (
	"meituan/apps/shop/models"
	db2 "meituan/db"
	"strconv"

	"github.com/gin-gonic/gin"
)

func ListCategory(ctx *gin.Context) {
	categorys := make([]models.Category, 10)
	db, _ := db2.NewDB()
	defer db.Close()
	db.Model(&models.Category{}).Find(&categorys)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": categorys,
	})
}

func DeleteCategory(ctx *gin.Context) {
	id := ctx.Param("id")
	numId, e := strconv.Atoi(id)
	if e != nil {
		ctx.JSON(404, gin.H{
			"code": 404,
			"msg":  "未找到分类",
		})
	}
	db, _ := db2.NewDB()
	defer db.Close()

	category := &models.Category{}
	category.ID = uint(numId)
	db.Model(category).Delete(category)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func UpdateCategory(ctx *gin.Context) {
	id := ctx.Param("id")
	numId, e := strconv.Atoi(id)
	if e != nil {
		ctx.JSON(404, gin.H{
			"code": 404,
			"msg":  "未找到分类",
		})
	}
	category := new(models.Category)
	err := ctx.ShouldBindJSON(category)

	if err != nil {
		ctx.JSON(400, gin.H{
			"code": 400,
			"msg":  err.Error(),
		})
	}
	category.ID = uint(numId)
	db, _ := db2.NewDB()
	defer db.Close()
	db.Model(category).Where("id").Update(category)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "修改成功",
		"data": category,
	})
}

func AddCategory(ctx *gin.Context) {
	category := new(models.Category)

	err := ctx.ShouldBindJSON(category)

	if err != nil {
		ctx.JSON(400, gin.H{
			"code": 400,
			"msg":  err.Error(),
		})
	}
	db, _ := db2.NewDB()
	defer db.Close()
	db.Model(category).Save(category)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "新建成功",
		"data": category,
	})
}
